/*
 * COPYRIGHT. ShenZhen iByte Technology Co., Ltd. 2018.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen iByte Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * Dec 3, 2018    Li.shangzhi         Create the class
 */
package com.github.icloud.elasticsearch.api.search;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

import com.github.icloud.elasticsearch.ElasticsearchClientBase;
/**
 * @FileName ScrollsAPI.java
 * @Description: Scroll API可以允许我们检索大量数据（甚至全部数据）
 *
 *	官方文档 @see <a href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-search-scrolling.html'></a>
 *	
 * @Date Dec 3, 2018 2:59:35 PM
 * @author Li.shangzhi
 * @version 1.0
 */
public class ScrollsAPI extends ElasticsearchClientBase{

	private String scrollId;

	@Test
	public void iEsScrolls() throws Exception{
		SearchResponse scrollResp = client.prepareSearch("icloud-iot-log")
				.addSort(FieldSortBuilder.DOC_FIELD_NAME,SortOrder.DESC)
				.setScroll(new TimeValue(60000)) //为了使用 scroll，初始搜索请求应该在查询中指定 scroll 参数，告诉 Elasticsearch 需要保持搜索的上下文环境多长时间（滚动时间）
				.setQuery(QueryBuilders.termQuery("user", "ibyte"))    // Query 查询条件
				.setSize(5).get(); 
		
		scrollId = scrollResp.getScrollId();
		do {
            for (SearchHit hit : scrollResp.getHits().getHits()) {

                System.out.println("" + hit.getSource().toString());
            }

            scrollResp = client.prepareSearchScroll(scrollId).setScroll(new TimeValue(60000)).execute().actionGet();
        }
        while (scrollResp.getHits().getHits().length != 0); 

	}

}
